<script setup lang="ts">
/**
 * @name RemoteAutomaticMeterReading
 * @description 远程自动抄表
 */
import { SearchForm } from './components'
import { defaultPagingParams } from './index'
import type {
  TableColumn,
} from '@/types'
import type { RemoteMonitoringResult } from '@/types/modules/api-remoteMonitoring​'
import { remoteMonitoringApi } from '@/api'

useCurrentInstance()
const { withLoading, loading } = useDefineLoading()
const [tableData, setTableData] = useState<
  RemoteMonitoringResult[]
>([])
const [total, setTotal] = useState<number>(0)
useState<string>('')

const columns: TableColumn<RemoteMonitoringResult>[] = [
  {
    key: uuid(),
    type: 'index',
    label: '序号',
  },
  {
    key: uuid(),
    label: '用能单元',
    prop: 'pointName',
  },
  {
    key: uuid(),
    label: '计量器具编号',
    prop: 'code',
  },
  {
    key: uuid(),
    label: '计量器具名称',
    prop: 'name',
    minWidth: 150,
  },
  // {
  //   key: uuid(),
  //   label: '安装位置',
  //   minWidth: 120,
  //   render({ row }) {
  //     return row.installationLocation ?? '---'
  //   },
  // },
  // {
  //   key: uuid(),
  //   label: '运行状态',
  //   minWidth: 120,
  //   render({ row }) {
  //     return row.workingStatusName ?? '---'
  //   },
  // },
  {
    key: uuid(),
    label: '抄表时间',
    prop: 'dataTime',
    minWidth: 130,
  },
  {
    key: uuid(),
    label: '上期读数(未乘倍率)',
    prop: 'lastReadingUntreated',
    render({ row }) {
      return row.lastReadingUntreated ?? '---'
    },
  },
  {
    key: uuid(),
    label: '上期读数',
    prop: 'lastReading',
    render({ row }) {
      return row.lastReading ?? '---'
    },
  },
  {
    key: uuid(),
    label: '本期读数(未乘倍率)',
    prop: 'thisReadingUntreated',
    render({ row }) {
      return row.thisReadingUntreated ?? '---'
    },
  },
  {
    key: uuid(),
    label: '本期读数',
    prop: 'thisReading',
    render({ row }) {
      return row.thisReading ?? '---'
    },
  },
  {
    key: uuid(),
    label: '倍率',
    prop: 'indicatorMultiple',
    render({ row }) {
      return row.indicatorMultiple ?? '---'
    },
  },
  {
    key: uuid(),
    label: '阶段用量',
    render({ row }) {
      if (
        row.stagUsage == null
        || (row.lastReading == null && row.thisReading == null)
      ) {
        return '---'
      }
      else if (!row.lastReading) {
        return '上期读数为空'
      }
      else if (!row.thisReading) {
        return '本期读数为空'
      }
      else {
        return row.stagUsage.toFixed(2)
      }
    },
  },
]
const pagingParams = ref({
  ...defaultPagingParams,
})

async function getTableData() {
  try {
    const { data: res } = await withLoading(
      remoteMonitoringApi.selectRemoteMonitoringPage,
    )(pagingParams.value)
    const { records, total } = res
    setTotal(total)
    setTableData(records)
  }
  catch (e) {
    setTotal(0)
    setTableData([])
  }
}
async function handleClickNode(row: any) {
  pagingParams.value.pointId = row.id
  await nextTick()
}

const [downloading, setDownloading] = useState(false)
async function handleDownload() {
  if (downloading.value)
    return
  setDownloading(true)
  const instance = ElMessage.warning({
    message: '导出中，请稍后',
    duration: 0,
  })
  try {
    const { data } = await remoteMonitoringApi.exportRemoteMonitoring1(
      pagingParams.value,
    )
    if (data?.url) {
      window.open(data.url)
    }
  }
  catch (e) {
    console.warn(e)
  }
  finally {
    setDownloading(false)
    instance.close()
  }
}

/** 能源品种切换后，如果没有能源品种，清空表格数据 */
watch(() => pagingParams.value.energyCode, (val: any) => {
  if (!val) {
    setTableData([])
    setTotal(0)
  }
})
// #endregion
</script>

<template>
  <div class="padding-sm flex gap-col-sm container">
    <ReadonlyPointTree fire @click-node="handleClickNode" />
    <div
      class="flex-direction overflow flex-fillRemaining flex align-end"
    >
      <ViewTable
        :loading="loading"
        :columns="columns"
        :data="tableData"
        custom-download
        :show-toolbox="true"
        border
        @download="handleDownload"
      >
        <template #actions>
          <SearchForm
            v-model="pagingParams"
            :downloading="downloading"
            :disable-download="tableData.length === 0"
            :point-id="pagingParams.pointId"
            @search="getTableData"
            @reset="getTableData"
          />
        </template>
      </ViewTable>

      <!-- 分页 -->
      <ListsPagination
        v-model:page-num="pagingParams.pageNumber"
        v-model:page-size="pagingParams.pageSize"
        :total="total"
        @current-change="getTableData"
        @size-change="getTableData"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
//-------------样式穿透-------------
</style>
